//
//  CameraViewController.swift
//  replaykit
//
//  Created by zhang on 2025/7/31.
//

import UIKit
import AVFoundation
import Photos
import WebRTC

class CameraViewController: UIViewController {
    
    // MARK: - AVFoundation Properties
    private let session = AVCaptureSession()
    private var previewLayer: AVCaptureVideoPreviewLayer?
    private var photoOutput: AVCapturePhotoOutput?
    private var videoDataOutput: AVCaptureVideoDataOutput?
    private var isCameraReady = false
    
    // MARK: - WebRTC Properties
    private var peerConnection: RTCPeerConnection?
    private var localVideoTrack: RTCVideoTrack?
    private var videoSource: RTCVideoSource?
    private var isStreaming = false
    
    // MARK: - RTMP Properties
    private var isRTMPStreaming = false
    
    // MARK: - Streaming Configuration
    private let rtmpURL = "rtmp://192.168.1.25:1935/live/stream"
    private let streamName = "stream"
    
    // MARK: - Streaming Manager
    private var streamingManager: StreamingManager?
    
    // MARK: - UI Elements
    private lazy var captureButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = .white
        button.layer.cornerRadius = 35
        button.layer.borderWidth = 4
        button.layer.borderColor = UIColor.white.cgColor
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(captureButtonTapped), for: .touchUpInside)
        
        // 添加阴影效果
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOffset = CGSize(width: 0, height: 2)
        button.layer.shadowOpacity = 0.5
        button.layer.shadowRadius = 4
        
        // 设置按钮标题
        button.setTitle("拍照", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        
        print("CameraViewController: 创建拍照按钮")
        return button
    }()
    
    private lazy var streamButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = .systemRed
        button.layer.cornerRadius = 30
        button.layer.borderWidth = 3
        button.layer.borderColor = UIColor.white.cgColor
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(streamButtonTapped), for: .touchUpInside)
        
        // 添加阴影效果
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOffset = CGSize(width: 0, height: 2)
        button.layer.shadowOpacity = 0.5
        button.layer.shadowRadius = 4
        
        // 设置按钮标题
        button.setTitle("推流", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        
        print("CameraViewController: 创建推流按钮")
        return button
    }()
    
    private lazy var statusLabel: UILabel = {
        let label = UILabel()
        label.text = "相机运行中"
        label.textColor = .white
        label.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 14)
        label.layer.cornerRadius = 8
        label.layer.masksToBounds = true
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        print("CameraViewController: viewDidLoad")
        
        setupUI()
        setupCamera()
        setupWebRTC()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("CameraViewController: viewWillAppear")
        
        // 启动相机会话
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            self?.session.startRunning()
            print("CameraViewController: 相机会话已启动")
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        print("CameraViewController: viewWillDisappear")
        
        // 停止相机会话
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            self?.session.stopRunning()
            print("CameraViewController: 相机会话已停止")
        }
        
        // 停止推流
        stopStreaming()
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        print("CameraViewController: 开始设置UI")
        
        // 添加状态标签
        view.addSubview(statusLabel)
        
        // 添加拍照按钮
        view.addSubview(captureButton)
        print("CameraViewController: 拍照按钮已添加到视图")
        
        // 添加推流按钮
        view.addSubview(streamButton)
        print("CameraViewController: 推流按钮已添加到视图")
        
        // 设置约束
        NSLayoutConstraint.activate([
            // 状态标签约束
            statusLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            statusLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            statusLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 120),
            statusLabel.heightAnchor.constraint(equalToConstant: 30),
            
            // 拍照按钮约束
            captureButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            captureButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            captureButton.widthAnchor.constraint(equalToConstant: 70),
            captureButton.heightAnchor.constraint(equalToConstant: 70),
            
            // 推流按钮约束
            streamButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30),
            streamButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            streamButton.widthAnchor.constraint(equalToConstant: 60),
            streamButton.heightAnchor.constraint(equalToConstant: 60)
        ])
        
        print("CameraViewController: UI约束已设置")
        print("CameraViewController: 拍照按钮frame: \(captureButton.frame)")
        print("CameraViewController: 推流按钮frame: \(streamButton.frame)")
        
        // 强制布局更新
        view.layoutIfNeeded()
        
        // 确保按钮在最上层
        ensureButtonsOnTop()
    }
    
    private func ensureButtonsOnTop() {
        print("CameraViewController: 确保按钮在最上层")
        
        // 将按钮移到最前面
        view.bringSubviewToFront(captureButton)
        view.bringSubviewToFront(streamButton)
        view.bringSubviewToFront(statusLabel)
        
        // 设置zPosition确保按钮在最上层
        captureButton.layer.zPosition = 1000
        streamButton.layer.zPosition = 1000
        statusLabel.layer.zPosition = 1000
        
        print("CameraViewController: 按钮zPosition设置完成")
        print("CameraViewController: 拍照按钮可见性: \(captureButton.isHidden)")
        print("CameraViewController: 推流按钮可见性: \(streamButton.isHidden)")
    }
    
    // MARK: - Camera Setup
    private func setupCamera() {
        print("CameraViewController: 开始设置相机")
        
        // 检查权限
        checkCameraPermission { [weak self] granted in
            DispatchQueue.main.async {
                if granted {
                    self?.configureCamera()
                } else {
                    print("CameraViewController: 相机权限被拒绝")
                    self?.showError("相机权限被拒绝")
                }
            }
        }
    }
    
    private func checkCameraPermission(completion: @escaping (Bool) -> Void) {
        print("CameraViewController: 检查相机权限")
        
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            print("CameraViewController: 相机权限已授权")
            completion(true)
        case .notDetermined:
            print("CameraViewController: 请求相机权限")
            AVCaptureDevice.requestAccess(for: .video) { granted in
                print("CameraViewController: 权限请求结果: \(granted)")
                completion(granted)
            }
        case .denied, .restricted:
            print("CameraViewController: 相机权限被拒绝或受限")
            completion(false)
        @unknown default:
            print("CameraViewController: 未知权限状态")
            completion(false)
        }
    }
    
    private func configureCamera() {
        print("CameraViewController: 配置相机设备")
        
        // 检查是否在模拟器环境中
        #if targetEnvironment(simulator)
        print("CameraViewController: 检测到模拟器环境")
        DispatchQueue.main.async {
            self.showError("模拟器不支持相机功能，请在真机上测试")
        }
        return
        #endif
        
        // 获取后置相机
        guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
            print("CameraViewController: 无法获取后置相机设备")
            showError("无法获取相机设备")
            return
        }
        
        print("CameraViewController: 成功获取相机设备: \(device.localizedName)")
        
        // 创建输入
        guard let input = try? AVCaptureDeviceInput(device: device) else {
            print("CameraViewController: 无法创建相机输入")
            showError("无法创建相机输入")
            return
        }
        
        // 创建拍照输出
        let photoOutput = AVCapturePhotoOutput()
        
        // 创建视频数据输出（用于推流）
        let videoDataOutput = AVCaptureVideoDataOutput()
        videoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global(qos: .userInitiated))
        videoDataOutput.videoSettings = [
            kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
        ]
        
        // 在后台线程配置session
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            
            // 开始配置session
            self.session.beginConfiguration()
            
            // 添加输入
            self.session.addInput(input)
            
            // 添加拍照输出
            self.session.addOutput(photoOutput)
            self.photoOutput = photoOutput
            
            // 添加视频数据输出
            self.session.addOutput(videoDataOutput)
            self.videoDataOutput = videoDataOutput
            
            // 提交配置
            self.session.commitConfiguration()
            
            print("CameraViewController: 相机配置完成")
            
            // 在主线程通知UI相机已准备就绪
            DispatchQueue.main.async {
                self.isCameraReady = true
                print("CameraViewController: 相机准备就绪，通知UI更新")
                
                // 设置预览层
                self.setupPreviewLayer()
                
                // 延迟一下再通知UI更新，确保会话完全启动
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                    print("CameraViewController: 最终通知UI更新")
                }
            }
        }
    }
    
    private func setupPreviewLayer() {
        print("CameraViewController: 设置预览层")
        
        // 创建预览层
        let previewLayer = AVCaptureVideoPreviewLayer(session: session)
        previewLayer.videoGravity = .resizeAspectFill
        previewLayer.frame = view.bounds
        
        // 将预览层添加到视图
        view.layer.addSublayer(previewLayer)
        
        // 保存引用
        self.previewLayer = previewLayer
        
        print("CameraViewController: 预览层已设置")
        print("CameraViewController: 预览层frame: \(previewLayer.frame)")
        print("CameraViewController: 相机会话运行状态: \(session.isRunning)")
        
        // 标记相机准备就绪
        isCameraReady = true
        
        // 确保按钮在最上层
        ensureButtonsOnTop()
    }
    
    // MARK: - WebRTC Setup
    private func setupWebRTC() {
        print("CameraViewController: 开始设置WebRTC")
        
        // 创建WebRTC配置
        let config = RTCConfiguration()
        config.iceServers = [
            RTCIceServer(urlStrings: ["stun:stun.l.google.com:19302"])
        ]
        
        // 创建PeerConnection工厂
        let factory = RTCPeerConnectionFactory()
        
        // 创建约束
        let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)
        
        // 创建PeerConnection
        peerConnection = factory.peerConnection(with: config, constraints: constraints, delegate: self)
        
        // 创建视频源
        videoSource = factory.videoSource()
        
        // 创建视频轨道
        localVideoTrack = factory.videoTrack(with: videoSource!, trackId: "video0")
        
        // 添加本地视频轨道到PeerConnection
        peerConnection?.add(localVideoTrack!, streamIds: ["stream0"])
        
        // 初始化StreamingManager
        streamingManager = StreamingManager(rtmpURL: rtmpURL, streamName: streamName)
        streamingManager?.onStreamingStatusChanged = { [weak self] streaming in
            DispatchQueue.main.async {
                self?.isRTMPStreaming = streaming
                self?.updateStreamButton()
                self?.updateStatusLabel()
            }
        }
        streamingManager?.onError = { [weak self] error in
            DispatchQueue.main.async {
                self?.showError(error)
            }
        }
        
        print("CameraViewController: WebRTC设置完成")
    }
    
    // MARK: - Streaming Control
    private func startStreaming() {
        print("CameraViewController: 开始推流")
        
        guard !isStreaming else {
            print("CameraViewController: 已经在推流中")
            return
        }
        
        // 开始RTMP推流
        startRTMPStreaming()
        
        isStreaming = true
        updateStreamButton()
        updateStatusLabel()
        
        print("CameraViewController: 推流已开始")
    }
    
    private func stopStreaming() {
        print("CameraViewController: 停止推流")
        
        guard isStreaming else {
            print("CameraViewController: 当前没有在推流")
            return
        }
        
        // 停止RTMP推流
        stopRTMPStreaming()
        
        isStreaming = false
        updateStreamButton()
        updateStatusLabel()
        
        print("CameraViewController: 推流已停止")
    }
    
    // MARK: - RTMP Streaming
    
    private func startRTMPStreaming() {
        print("CameraViewController: 开始RTMP推流到: \(rtmpURL)")
        
        // 使用StreamingManager开始推流
        let success = streamingManager?.startStreaming() ?? false
        if success {
            isRTMPStreaming = true
            updateStatusLabel()
            showSuccess("RTMP推流已开始")
        } else {
            showError("RTMP推流失败")
        }
    }
    
    private func stopRTMPStreaming() {
        print("CameraViewController: 停止RTMP推流")
        
        streamingManager?.stopStreaming()
        isRTMPStreaming = false
        updateStatusLabel()
        showSuccess("RTMP推流已停止")
    }
    
    // MARK: - UI Updates
    private func updateStreamButton() {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            
            if self.isStreaming {
                self.streamButton.backgroundColor = .systemOrange
                self.streamButton.setTitle("停止", for: .normal)
            } else {
                self.streamButton.backgroundColor = .systemRed
                self.streamButton.setTitle("推流", for: .normal)
            }
        }
    }
    
    private func updateStatusLabel() {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            
            if self.isStreaming {
                if self.isRTMPStreaming {
                    self.statusLabel.text = "RTMP推流中..."
                } else {
                    self.statusLabel.text = "推流中..."
                }
            } else {
                self.statusLabel.text = "相机运行中"
            }
        }
    }
    
    // MARK: - Actions
    @objc private func captureButtonTapped() {
        print("CameraViewController: 拍照按钮被点击")
        
        guard let photoOutput = photoOutput else {
            print("CameraViewController: 拍照输出未初始化")
            return
        }
        
        // 防止重复点击
        captureButton.isEnabled = false
        
        // 添加按钮动画
        UIView.animate(withDuration: 0.1, animations: {
            self.captureButton.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        }) { _ in
            UIView.animate(withDuration: 0.1) {
                self.captureButton.transform = CGAffineTransform.identity
            }
        }
        
        // 拍照
        let settings = AVCapturePhotoSettings()
        photoOutput.capturePhoto(with: settings, delegate: self)
        
        // 延迟恢复按钮
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.captureButton.isEnabled = true
        }
    }
    
    @objc private func streamButtonTapped() {
        print("CameraViewController: 推流按钮被点击")
        
        if isStreaming {
            stopStreaming()
        } else {
            startStreaming()
        }
    }
    
    // MARK: - Error Handling
    private func showError(_ message: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: "错误", message: message, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "确定", style: .default))
            self.present(alert, animated: true)
        }
    }
}

// MARK: - AVCapturePhotoCaptureDelegate
extension CameraViewController: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        print("CameraViewController: 拍照完成")
        
        if let error = error {
            print("CameraViewController: 拍照错误: \(error.localizedDescription)")
            showError("拍照失败: \(error.localizedDescription)")
            return
        }
        
        guard let imageData = photo.fileDataRepresentation(),
              let image = UIImage(data: imageData) else {
            print("CameraViewController: 无法获取照片数据")
            showError("无法获取照片数据")
            return
        }
        
        // 保存到相册
        savePhotoToAlbum(image)
    }
    
    private func savePhotoToAlbum(_ image: UIImage) {
        print("CameraViewController: 开始保存照片到相册")
        
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            DispatchQueue.main.async {
                switch status {
                case .authorized, .limited:
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }) { success, error in
                        DispatchQueue.main.async {
                            if success {
                                print("CameraViewController: 照片保存成功")
                                self?.showSuccess("照片已保存到相册")
                            } else {
                                print("CameraViewController: 照片保存失败: \(error?.localizedDescription ?? "未知错误")")
                                self?.showError("照片保存失败: \(error?.localizedDescription ?? "未知错误")")
                            }
                        }
                    }
                case .denied, .restricted:
                    print("CameraViewController: 相册权限被拒绝")
                    self?.showError("需要相册权限来保存照片")
                case .notDetermined:
                    print("CameraViewController: 相册权限未确定")
                    self?.showError("需要相册权限来保存照片")
                @unknown default:
                    print("CameraViewController: 未知相册权限状态")
                    self?.showError("需要相册权限来保存照片")
                }
            }
        }
    }
    
    private func showSuccess(_ message: String) {
        let alert = UIAlertController(title: "成功", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}

// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension CameraViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        // 只在推流时处理视频数据
        guard isStreaming else { return }
        
        // 将CMSampleBuffer转换为RTCVideoFrame
        guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
        
        let rtcPixelBuffer = RTCCVPixelBuffer(pixelBuffer: pixelBuffer)
        let frame = RTCVideoFrame(buffer: rtcPixelBuffer, rotation: ._0, timeStampNs: Int64(CACurrentMediaTime() * 1000000000))
        
        // 发送到WebRTC - 使用正确的API
        DispatchQueue.main.async { [weak self] in
            self?.videoSource?.adaptOutputFormat(toWidth: 640, height: 480, fps: 30)
            // 注意：这里暂时注释掉视频帧发送，因为WebRTC API可能需要不同的方法
            // self?.videoSource?.captureFrame(frame)
        }
        
        // 处理真正的推流
        if isRTMPStreaming {
            streamingManager?.processVideoFrame(pixelBuffer)
        }
        
        print("CameraViewController: 视频帧已处理")
    }
}

// MARK: - RTCPeerConnectionDelegate
extension CameraViewController: RTCPeerConnectionDelegate {
    func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {
        print("CameraViewController: 信令状态改变: \(stateChanged.rawValue)")
    }
    
    func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {
        print("CameraViewController: 添加媒体流")
    }
    
    func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {
        print("CameraViewController: 移除媒体流")
    }
    
    func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {
        print("CameraViewController: 需要协商")
    }
    
    func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {
        print("CameraViewController: ICE连接状态改变: \(newState.rawValue)")
    }
    
    func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {
        print("CameraViewController: ICE收集状态改变: \(newState.rawValue)")
    }
    
    func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {
        print("CameraViewController: 生成ICE候选")
    }
    
    func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {
        print("CameraViewController: 移除ICE候选")
    }
    
    func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {
        print("CameraViewController: 打开数据通道")
    }
} 